package com.example.park

import android.os.Bundle
import android.widget.PopupMenu
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import androidx.paging.PagingData
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.base.entity.ParkEntityItem
import com.example.base.mvi.BaseActivity
import com.example.base.mvi.HttpType
import com.example.base.mvi.UiState
import com.example.park.databinding.ActivityParkBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@Route(path = "/park/ParkActivity")
@AndroidEntryPoint
class ParkActivity : BaseActivity<ActivityParkBinding,ParkIntent,ParkViewModel>() {
    //val parkPageAdapter by lazy { ParkPageAdapter() }
    val parkAdapter by lazy { ParkAdapter() }
    var position = -1
    var type = "类型"//刷选条件
    override fun getLayout(): Int  = R.layout.activity_park

    override fun getVM(): Class<ParkViewModel>  = ParkViewModel::class.java

    override fun initView() {
        binding.rv.apply {
            //adapter = parkPageAdapter
            adapter = parkAdapter
            layoutManager = LinearLayoutManager(this@ParkActivity)
        }

        //新增
        binding.head.apply {
            headBack.setOnClickListener {
                finish()
            }
            headAdd.setOnClickListener {
                ARouter.getInstance().build("/park/ParkEditActivity").navigation()
            }
        }
        //点击item,跳转到详情界面，进行修改保存
        parkAdapter.setOnItemClickListener { adapter, view, position ->
            ARouter.getInstance().build("/park/ParkEditActivity").withInt("pid",parkAdapter.data[position].id).navigation()
        }
        //左滑删除
        ItemTouchHelper(object :ItemTouchHelper.Callback(){
            override fun getMovementFlags(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder
            ): Int {
                val left = ItemTouchHelper.LEFT
                return makeMovementFlags(0,left)
            }

            override fun onMove(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder,
                target: RecyclerView.ViewHolder
            ): Boolean {
                return true
            }

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                //局部更新
                position = viewHolder.layoutPosition
                //发送请求
                viewModel.sendIntent(ParkIntent.parkDelete(parkAdapter.data[position].id))
            }
        }).attachToRecyclerView(binding.rv)

        //长按常看vr图
        parkAdapter.setOnItemLongClickListener { adapter, view, position ->
            ARouter.getInstance().build("/park/ParkVrActivity").navigation()
            return@setOnItemLongClickListener true
        }
        //点击筛选图标，弹出条件  车牌号 车位状态 所在区域
        binding.ivFilter.setOnClickListener {
            val popupMenu = PopupMenu(this,binding.ivFilter)
            popupMenu.inflate(R.menu.menu_filter)
            popupMenu.setOnMenuItemClickListener {
                when(it.itemId){
                    R.id.carNo->{
                        type = "车牌号"
                    }
                    R.id.status->{
                        type = "状态"
                    }
                    R.id.area->{
                        type = "所在区域"
                    }
                }
                true
            }
            popupMenu.show()
        }

        //使用searchview实现搜索
        binding.sv.setOnQueryTextListener(object :SearchView.OnQueryTextListener{
            override fun onQueryTextSubmit(query: String?): Boolean {
                if(query!=null){
                    when(type){
                        "车牌号"->{
                            viewModel.sendIntent(ParkIntent.parkCarNo(query))
                        }
                        "状态"->{
                            viewModel.sendIntent(ParkIntent.parkStatus(query))
                        }
                        "所在区域"->{
                            viewModel.sendIntent(ParkIntent.parkArea(query.toInt()))
                        }
                        else->{
                            viewModel.sendIntent(ParkIntent.parkType("标准车位"))
                        }
                    }
                }
                return true
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                if(newText!=null){
                    if(type=="车牌号"){
                        //实时查询
                        val list = parkAdapter.data.filter {newText in it.licensePlate  }

                        parkAdapter.data.clear()
                        parkAdapter.data.addAll(list)
                        parkAdapter.notifyDataSetChanged()
                    }
                }
                return true
            }
        })

    }

    override fun initData() {
        lifecycleScope.launch {
            viewModel.uiState.collect{
                when(it){

                    is UiState.onSuccess<*> -> {
                        when(it.type){
                            HttpType.DEFAULT -> {
                               /* val pagingData = it.data as PagingData<ParkEntityItem>
                                parkPageAdapter.submitData(pagingData)*/
                                val items = it.data as Collection<ParkEntityItem>
                                parkAdapter.data.clear()
                                parkAdapter.data.addAll(items.sortedByDescending { it.id })
                                parkAdapter.notifyDataSetChanged()
                            }
                            HttpType.DELETE->{
                                ToastUtils.showLong("删除成功")
                                parkAdapter.data.removeAt(position)
                                parkAdapter.notifyItemRemoved(position)
                            }
                           else->{}
                        }
                    }
                    else->{

                    }
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        viewModel.sendIntent(ParkIntent.parkType("标准车位"))
    }

}